import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import "./video.css";

const VideoPlay = () => {
    const [isVideoLooping, setIsVideoLooping] = useState(true);
    const [isRequestFinished, setIsRequestFinished] = useState(false);
    const videoRef = useRef<HTMLVideoElement>(null);
    const navigate = useNavigate();

    useEffect(() => {
        handleVideoPlay();
        return sendPrintRequest();
    }, []);

    const sendPrintRequest = () => {
        const timer = setTimeout(() => {
            setIsRequestFinished(true);
        }, 23000);

        return () => clearTimeout(timer);
    };

    const handleVideoPlay = () => {
        const video = videoRef.current;
        if (video) {
            video.play().catch((error) => {
                console.error("Error when playing video", error);
            });
        }
    };

    useEffect(() => {
        if (isRequestFinished) {
            setIsVideoLooping(false);
        }
    }, [isRequestFinished]);


    const handleVideoEnd = () => {
        navigate("/about");
    };

    useEffect(() => {
        const video = videoRef.current;
        if (video) {
            video.addEventListener("ended", handleVideoEnd);
            return () => {
                video.removeEventListener("ended", handleVideoEnd);
            };
        }
    }, [handleVideoEnd]);

    return (
        <div>
            <h2 >Printing API needs 23 seconds, and Video duration is 14 seconds.</h2>
            <p className="text-orange-600">{isRequestFinished ? "Bag Tag Printed" : "Bag Tag Printing..."}</p>
            <video
                ref={videoRef}
                controls
                autoPlay
                muted
                loop={isVideoLooping}
                width={860}
                height={260}
            >
                <source src="/ice-sea.mp4" type="video/mp4" />
            </video>
        </div>
    );
};

export default VideoPlay;
    